import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;

import fr.umlv.escapeir.GameWorld;
import fr.umlv.escapeir.game.EnnemyShipFactory;
import fr.umlv.escapeir.game.ShipCreationException;
import fr.umlv.escapeir.gesture.GestureHandler;
import fr.umlv.escapeir.painters.Scene;
import fr.umlv.escapeir.painters.ScrollingImageLayer;
import fr.umlv.zen2.Application;
import fr.umlv.zen2.ApplicationCode;
import fr.umlv.zen2.ApplicationContext;
import fr.umlv.zen2.ApplicationRenderCode;
import fr.umlv.zen2.MotionEvent;

public class JBox2DTest {

	/**
	 * @param args
	 * @throws ShipCreationException 
	 */
	public static void main(String[] args) throws ShipCreationException {
	    final int WIDTH = 400;
	    final int HEIGHT = 600;
		
		final GameWorld world = new GameWorld(WIDTH, HEIGHT);
		//Ajout d'un objet
		EnnemyShipFactory esf = new EnnemyShipFactory(world);
		esf.create("jupiter", 100, 300);
		//GestureHandler.self().registerListener(ship);
		
		ScrollingImageLayer sil1 = null;
		ScrollingImageLayer sil2 = null;
		try {
			sil1 = new ScrollingImageLayer("fr/umlv/escapeir/painters/images/jupi2.png", WIDTH, HEIGHT, 2f);
			sil2 = new ScrollingImageLayer("fr/umlv/escapeir/painters/images/jupicloud.png", WIDTH, HEIGHT, 4f);
		} catch (IOException e1) {
			System.err.println("Can't generate scrolling layer");
		}
		
		final Scene s = new Scene();
		s.addLayer(sil1);
		s.addLayer(sil2);
		s.addLayer(world);
		
		s.addLayer(GestureHandler.self());
		
		Application.run("ScrollIt", WIDTH, HEIGHT, new ApplicationCode() {
			@Override
			public void run(ApplicationContext context) {
				for(;;) {
					try {
						//Avoid flickering
						Thread.sleep(5);
					} catch (InterruptedException e) {
						new AssertionError("Rendering thread must not stop");
					}
					final MotionEvent event = context.pollMotion();
					if(event != null) {
						GestureHandler.self().receiveEvent(event);
					}
					
					context.render(new ApplicationRenderCode() {
						@Override
						public void render(Graphics2D graphics) {
							graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
							graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
							s.render(graphics);
						}
					});
				}
			}
		});
		
		for (;;) {
			
			if (world.step()) s.apply();
			try {
				Thread.sleep(17);
			} catch (InterruptedException e) {
				throw new AssertionError("Main thread should not be stopped.");
			}
		}
	}
}
